package com.thrsdk;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.thrsdk.common.network.request.HttpRequestClient;
import com.thrsdk.constants.ApiConstants;
import com.thrsdk.constants.AppConfig;
import com.thrsdk.constants.AppConstants;
import com.thrsdk.listener.IExitListener;
import com.thrsdk.listener.IListener;
import com.thrsdk.listener.IUserListener;
import com.thrsdk.listener.InitListener;
import com.thrsdk.listener.SDKListenerInfo;
import com.thrsdk.listener.UserListenerInfo;
import com.thrsdk.log.LogUtils;
import com.thrsdk.manager.AccountManager;
import com.thrsdk.model.data.PayInfo;
import com.thrsdk.model.data.RoleInfo;
import com.thrsdk.model.protocol.bean.CustomerBean;
import com.thrsdk.model.protocol.bean.InitDevice;
import com.thrsdk.model.protocol.bean.LoginMessage;
import com.thrsdk.model.protocol.bean.LoginTempMessage;
import com.thrsdk.model.protocol.bean.PayConfig;
import com.thrsdk.model.protocol.bean.ResCertificate;
import com.thrsdk.model.protocol.bean.ShareBean;
import com.thrsdk.mylibrary.BuildConfig;
import com.thrsdk.ui.dialog.Exitdialog;
import com.thrsdk.ui.dialog.LoginDialog;
import com.thrsdk.ui.dialog.PayDialog;
import com.thrsdk.ui.dialog.SwitchAccountdialog;
import com.thrsdk.utils.DomainHelper;
import com.thrsdk.utils.DyPhoneUtils;
import com.thrsdk.utils.GameCofig;
import com.thrsdk.utils.OaidListener;
import com.thrsdk.utils.ToastUtils;

import java.util.TreeMap;


public class THFSDKClient extends DYFusionSDK {
    private static Context mContext = null;
    private Exitdialog exitdialog;
    private static IUserListener mIKLUserListener;
    private static SDKListenerInfo apiListenerInfo;
    private UserListenerInfo switchListener;
    private static IListener<LoginMessage> mILoginListener;

    protected THFSDKClient() {
    }

    @Override
    public Context getContext() {
        return mContext;
    }

    @Override
    public String getChannelNumber(Activity act) {
        return GameCofig.getChannelNumber(act);
    }

    //todo 2022.07.04 增加平台标识
    @Override
    public String getPlatformNumber(Activity activity) {
        return GameCofig.getPlatformNumber(activity);
    }

    @Override
    public void onMainUserCenter(Activity activity) {
        LogUtils.getInstance().d("调起用户中心");
        ToastUtils.showShortSafe(activity, "调起用户中心");
    }

    // TODO: 2023-04-23 增加分享
    @Override
    public void onShare(Activity activity, ShareBean shareBean, IListener<String> iShareListener) {
        ToastUtils.showShortSafe(activity, "调起分享");
        LogUtils.getInstance().d("调起onShare");

    }

    // TODO: 2023-04-23 增加客服
    @Override
    public void onCustomerService(Activity activity, CustomerBean customerBean) {
        ToastUtils.showShortSafe(activity, "调起客服:" + customerBean.getDescribe());
        LogUtils.getInstance().d("调起onCustomerService");

    }

    @Override
    public void onThirdCenter(Activity activity, IListener<LoginMessage> thirdlistener) {
        ToastUtils.showShortSafe(activity, "调起第三方登陆");
        LogUtils.getInstance().d("调起第三方登陆");
    }

    @Override
    public void onGetPriceCurrencySuccess(Activity activity, String productid, IListener<String> getcurrencylistener) {
        Toast.makeText(activity, "调起获取账号货币单位", Toast.LENGTH_SHORT).show();
        LogUtils.getInstance().d("当前计费点:" + productid);
        if (null != getcurrencylistener) {
            getcurrencylistener.onSuccess("");
        }
    }

    @Override
    public void onEventReport(Activity activity, String eventName, String jsonevent) {
        Toast.makeText(activity, "调起统计事件上报:" + eventName + jsonevent, Toast.LENGTH_SHORT).show();
        LogUtils.getInstance().d("调起统计事件上报:" + eventName + jsonevent);
        Log.d("调起统计事件上报:" + eventName, jsonevent);
    }

    InitDevice initDevicedata;

    /**
     * 初始化接口
     *
     * @param appid
     * @param appkey
     */
    @Override
    public void initInterface(final Activity activity, String appid, String appkey, final InitListener listener) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_INIT, activity, appid, appkey, listener);
        try {
            mContext = activity;
            AppConstants.appId = appid;
            AppConstants.appKey = appkey;
            AppConstants.sdkVer = BuildConfig.VERSION_NAME;


            DomainHelper.getInstance().getDomainListFromNet(activity, 0);

            DyPhoneUtils.isReadyAndroidOAID(activity, new OaidListener() {
                @Override
                public void OnGet(String oaid) {

                    //获取设备ID
                    TreeMap<String, String> map = new TreeMap<>();
                    map.put("os", "2");
                    map.put("mobileId", DyPhoneUtils.initDeviceUniqueId(activity));
                    map.put("oaid", oaid);
                    map.put("terminalType", "2");
                    HttpRequestClient.sendPostRequest(ApiConstants.ACTION_INITDEVICE, map, InitDevice.class, new HttpRequestClient.ResultHandler<InitDevice>(activity) {
                        @Override
                        public void onSuccess(InitDevice initDevicedata, boolean result, String msg) {
                            if (result) {
                                THFSDKClient.this.initDevicedata = initDevicedata;
                                listener.Success(initDevicedata.data.uuid);
                            } else {
                                listener.fail(msg);
                            }
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            listener.fail("");
                        }
                    });

                }
            });


        } catch (Throwable e) {
            listener.fail("初始化失败！");
            LogUtils.getInstance().e(e, "初始化失败");
        }
    }

    /**
     * 登录接口
     *
     * @param activity
     * @param listener
     */
    @Override
    public void login(Activity activity, IListener<LoginMessage> listener) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_LOGIN, activity, AppConstants.appId, AppConstants.appKey, listener);
        try {
            if (AppConfig.isLogining) {
                LogUtils.getInstance().d("不能重复调用登录,请上一次登录结束！！！");
                return;
            }
            AppConfig.isLogining = true;
            mILoginListener = listener;

            LoginDialog loginDialog = new LoginDialog(activity, listener);
            loginDialog.setmLoginInterface(new LoginDialog.LoginInterface() {
                @Override
                public void clickLogin(String str_loginname) {

                    TreeMap<String, String> map = new TreeMap<>();
                    map.put("loginName", str_loginname);
                    map.put("loginPass", "123456");
                    if (null != initDevicedata) {
                        map.put("uuid", TextUtils.isEmpty(initDevicedata.data.uuid) ? "" : initDevicedata.data.uuid);
                    }
                    HttpRequestClient.sendPostRequest(ApiConstants.ACTION_FUSIONLOGIN, map, LoginTempMessage.class, new HttpRequestClient.ResultHandler<LoginTempMessage>(activity) {
                        @Override
                        public void onSuccess(LoginTempMessage loginTempMessage, boolean result, String msg) {
                            if (result) {
                                LoginMessage loginMessage = new LoginMessage();
                                loginMessage.setOpenId(loginTempMessage.getData().getOpenId());
                                loginMessage.setToken(loginTempMessage.getData().getToken());

                                loginMessage.setUserName(loginTempMessage.getData().getUserName());
                                loginMessage.setGameId(loginTempMessage.getData().getGameId());

                                AppConstants.setLoginInfo(loginMessage);
                                AppConfig.isLogining = false;
                                AppConstants.setLoginInfo(loginMessage);
                                listener.onSuccess(loginMessage);
                            } else {
                                AppConfig.isLogining = false;
                                listener.onFail(msg);
                            }
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            /**
                             * 登录失败
                             */
                            AppConfig.isLogining = false;
                            listener.onFail(t.getMessage());
                        }
                    });


                }
            });
            loginDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    AppConfig.isLogining = false;
                }
            });

            loginDialog.show();
        } catch (Exception e) {
            LogUtils.getInstance().e(e, "登录异常！");
            AppConfig.isLogining = false;
            listener.onFail(e.getMessage());
        }
    }

    @Override
    public void payment(Activity activity, PayInfo payInfo, SDKListenerInfo listener) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_PAYMENT, activity, payInfo, listener);
        if (TextUtils.isEmpty(AppConstants.openId)) {
            LogUtils.getInstance().d("支付异常, uid为空，登录异常");
            Toast.makeText(activity, "请登录后进行充值", Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            PayDialog payDialog = new PayDialog(activity, payInfo, listener);
            payDialog.setmPayInterface(new PayDialog.PayInterface() {
                @Override
                public void clickPay() {
                    TreeMap<String, String> map = new TreeMap<>();
                    map.put("jhToken", AppConstants.token);
                    map.put("gameOrderSerial", payInfo.getOrderid());
                    map.put("orderFee", payInfo.getAmount());
                    map.put("goodsName", payInfo.getProductName());
                    map.put("goodsDesc", payInfo.getProductName());
                    map.put("roleLevel", payInfo.getRolelevel());
                    map.put("roleName", payInfo.getRolename());
                    map.put("roleId", payInfo.getRoleid());
                    map.put("serverName", payInfo.getServername());
                    map.put("serverId", payInfo.getServerid());
                    map.put("traInfo", payInfo.getExtrainfo());
                    map.put("paySign", payInfo.getPaySign());
                    map.put("timestamp", payInfo.getTimestamp());
                    if (null != initDevicedata) {
                        map.put("uuid", TextUtils.isEmpty(initDevicedata.data.uuid) ? "" : initDevicedata.data.uuid);
                    }
                    if (!TextUtils.isEmpty(payInfo.getProductid())) {
                        map.put("goodsCode", payInfo.getProductid());
                    }
                    HttpRequestClient.sendPostRequest(ApiConstants.ACTION_FUSIONPAY, map, PayConfig.class, new HttpRequestClient.ResultHandler<PayConfig>(activity) {
                        @Override
                        public void onSuccess(PayConfig payConfig, boolean result, String msg) {
                            if (result) {
                                listener.onSuccess("");
                            } else {
                                listener.onFail(msg);
                            }
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            listener.onFail(t.getMessage());
                        }
                    });
                }
            });
            payDialog.show();
        } catch (Exception e) {
            LogUtils.getInstance().e(e, "支付异常！！！");
            e.printStackTrace();
        }
    }


    @Override
    public void exit(final Activity activity, final IExitListener exitlistener) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_EXIT, activity, exitlistener);
        exitdialog = new Exitdialog(activity, new Exitdialog.Exitdialoglistener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (v.getId() == AppConfig.resourceId(activity, "dialog_exit",
                        "id")) {
                    exitlistener.exitSuccess("success");
                    exitdialog.dismiss();
                } else if (v.getId() == AppConfig.resourceId(activity,
                        "dialog_cancel", "id")) {
                    exitlistener.fail("fail");
                    exitdialog.dismiss();
                }
            }
        });
        exitdialog.show();
    }

    @Override
    public void switchAccount() {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_SWITHACCOUNT);

        SwitchAccountdialog switchAccountdialog = new SwitchAccountdialog(mContext, new SwitchAccountdialog.SwitchAccountdialoglistener() {

            @Override
            public void onClickSwitchAccount() {
                AppConfig.isLogining = false;
                AppConfig.isShow = false;
                AccountManager.logout();
                switchListener.onLogout("");
            }
        });
        switchAccountdialog.show();


    }

    @Override
    public void getCertificateData(Context context, final IListener<ResCertificate> listener) {
        if (TextUtils.isEmpty(AppConstants.openId)) {
            LogUtils.getInstance().e(null, "openid为空，请先登录！");
            Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        /**
         * 若第三方无实名信息获取，直接返回此逻辑
         */
        ResCertificate resCertificate = new ResCertificate();
        resCertificate.setResult(false);
        resCertificate.setMsg("实名获取失败");
        listener.onSuccess(resCertificate);

    }


    /**
     * @param listener SDK主动退出回调接口
     */
    @Override
    public void setUserListener(final UserListenerInfo listener) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_SETUSERLISTER);
        /**
         * 如果SDK触登出逻辑  则调用  switchListener.onLogout("success");
         */
        switchListener = listener;
    }


    @Override
    public void setExtData(Context context, RoleInfo roleData) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_SETEXTDATA, context, roleData);
        try {
            if (TextUtils.isEmpty(AppConstants.openId)) {
                LogUtils.getInstance().superLog(5, "", null, "uid is null");
                Toast.makeText(context, "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            LogUtils.getInstance().d("角色上报", roleData);
        } catch (Exception e) {
            LogUtils.getInstance().e(e, "角色上报失败！", "msg=" + e.getMessage());
            ;
        }
    }

    /**
     * @param context 如果cp出现无法继承自身application的情况， 在application的oncreate方法调用applicationInit（Context context）
     */
    @Override
    public void applicationInit(Context context) {
        AppConfig.mApplication = new THFApplication();
        AppConfig.mApplication.onCreate();
        LogUtils.getInstance().d("applicationInit！");
    }

    @Override
    public void onStart(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONSTART);
    }

    @Override
    public void onCreate(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONCREATE);

    }

    @Override
    public void onStop(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONSTOP);
    }


    @Override
    public void onDestroy(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONDESTORY);
    }

    @Override
    public void onResume(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONRESUME);
    }


    @Override
    public void onPause(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONPAUSE);
    }

    @Override
    public void onRestart(Activity activity) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONRESTART);
    }

    @Override
    public void onNewIntent(Intent intent) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONNEWINTENT);
    }

    @Override
    public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONACTRESULT);
    }

    // 是否打开日志，要在Application的super.onCreate()之前调用，才能输出所有信息
    @Override
    public void openLog(Context context, boolean isopen) {
        LogUtils.getInstance().openDebug(isopen);
    }

    @Override
    public void onKeyDown(int keyCode, KeyEvent event) {
//        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONKEYDOWN);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_CONFCHANGED);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //LogUtils.getInstance().checkSDKMethod(LogUtils.SDK_ONREQPERRESULT);
    }

}
